import { NextRequest, NextResponse } from 'next/server';
import { ExecutionTrace } from '@/types';
import { initializeDatabase, getMessages, getExecutionTraces } from '@/lib/database';
import { withCors } from '@/lib/cors';

// Flowise 配置
const FLOWISE_API_URL = process.env.FLOWISE_API_URL || 'http://localhost:3001';
const FLOWISE_API_KEY = process.env.FLOWISE_API_KEY;

// 初始化数据库
let dbInitialized = false;
async function ensureDatabaseInitialized() {
  if (!dbInitialized) {
    await initializeDatabase();
    dbInitialized = true;
  }
}

async function handleGET(request: NextRequest) {
  try {
    await ensureDatabaseInitialized();
    
    const { searchParams } = new URL(request.url);
    const chatflowId = searchParams.get('chatflowId');
    const sessionId = searchParams.get('sessionId');

    if (!chatflowId || !sessionId) {
      return NextResponse.json(
        { error: '缺少必要参数: chatflowId 和 sessionId' },
        { status: 400 }
      );
    }

    // 从数据库获取消息和执行追踪
    const [chatMessages, executionTraces] = await Promise.all([
      getMessages(sessionId),
      getExecutionTraces(sessionId)
    ]);

    // 转换执行追踪格式
    const steps = executionTraces.map(trace => ({
      agentName: trace.stepType,
      nodeName: trace.stepName,
      input: trace.inputData,
      output: trace.outputData,
      status: trace.status,
      errorMessage: trace.errorMessage,
      duration: trace.duration,
      timestamp: trace.timestamp
    }));

    const response: ExecutionTrace = {
      steps,
      chatMessages: chatMessages.map(msg => ({
        role: msg.role,
        content: msg.content,
        timestamp: msg.timestamp,
      })),
    };

    return NextResponse.json(response);

  } catch (error) {
    console.error('获取追踪数据错误:', error);
    return NextResponse.json(
      { error: '获取执行追踪失败', details: error instanceof Error ? error.message : '未知错误' },
      { status: 500 }
    );
  }
}

// 导出带 CORS 支持的 GET 处理器
export const GET = withCors(handleGET);

// 处理 OPTIONS 预检请求
export async function OPTIONS(request: NextRequest) {
  const origin = request.headers.get('origin');
  const response = new NextResponse(null, { status: 200 });
  
  if (origin && ['http://localhost:3000', 'http://localhost:3001', 'http://localhost:3002'].includes(origin)) {
    response.headers.set('Access-Control-Allow-Origin', origin);
  }
  response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  response.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With, Accept, Origin');
  response.headers.set('Access-Control-Allow-Credentials', 'true');
  response.headers.set('Access-Control-Max-Age', '86400');
  
  return response;
}
